package com.luo.gmall.auth.config;

import com.luo.gmall.common.utils.RsaUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;

import javax.annotation.PostConstruct;
import java.io.File;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * @author Zoro
 * @date 2021年11月20
 */
@Data
@Slf4j
@ConfigurationProperties(prefix = "jwt")
public class JwtProperties {

    private String publicKeyPath;
    private String privateKeyPath;
    private String secret;
    private String cookieName;
    private Integer expire;
    private String unick;

    private PublicKey publicKey;

    private PrivateKey privateKey;

    @PostConstruct
    public void inti() {
        try {
            File publicFile = new File(publicKeyPath);
            File privateFile = new File(privateKeyPath);
            // 如果公钥私钥不存在，重新生成公钥私钥
            if (!publicFile.exists() || !privateFile.exists()) {
                RsaUtils.generateKey(publicKeyPath, privateKeyPath, secret);
            }
            this.publicKey = RsaUtils.getPublicKey(publicKeyPath);
            this.privateKey = RsaUtils.getPrivateKey(privateKeyPath);
        } catch (Exception e) {
            log.error("生成公钥私钥失败!");
            e.printStackTrace();
        }
    }


}
